﻿using System;
using System.Data;
using Dragon.Library.Framework.Interface.Dao;
using Dragon.Library.Utility.Config;
using Dragon.Library.Utility.NHibernate;
using NHibernate;

namespace Dragon.Library.Framework.Dao
{
    public abstract partial class BaseDao<T, TKeyT> : IBaseDao<T, TKeyT>
        where T : class,new()
    {
        private string _sessionKey;
        public string SessionKey
        {
            get { return _sessionKey; }
            set
            {
                _sessionKey = value;
            }
        }

        private bool _isTran;
        public bool IsTran
        {
            get { return _isTran; }
            set
            {
                _isTran = value;
                if (_isTran && Session != null)
                    Session.BeginTransaction();
            }
        }

        public bool IsOpen
        {
            get { return Session.Connection.State == ConnectionState.Open; }
        }

        private ISession _session;
        protected ISession Session
        {
            get
            {
                if (_session == null)
                    throw new NullReferenceException("Session未开启！");
                return _session;
            }
            private set { _session = value; }
        }

        private readonly string[] _pageQueryKeies;

        private string _configFileName;
        public string ConfigFileName
        {
            get { return _configFileName; }
            protected set
            {
                _configFileName = value;
                SessionFactory.InitConfig(_configFileName);
            }
        }

        public void Initialization(string sessionKey)
        {
            SessionKey = sessionKey;
            Session = SessionFactory.GetSession(SessionKey, ConfigFileName);
            if (IsTran)
                Session.BeginTransaction();
        }

        protected BaseDao(string[] pageQueryKeies)
        {
            ConfigFileName = "";
            _pageQueryKeies = pageQueryKeies;
        }

        protected BaseDao(string[] pageQueryKeies, string configKey)
        {
            _pageQueryKeies = pageQueryKeies;
            ConfigFileName = ConfigUtility.GetAppSettingsValue(configKey);
        }
    }
}
